import { defineStore } from 'pinia';
import axios from '../utils/axios';

// API基础URL - 已经在axios配置中设置了baseURL，这里保持定义以便于理解

export const useClothesStore = defineStore('clothes', {
  state: () => ({
    clothesList: [],
    selectedClothes: null,
    loading: false,
    error: null,
    filters: {
      type: '',
      color: '',
      season: '',
      occasion: '',
      favorite: false
    },
    pagination: {
      currentPage: 1,
      pageSize: 12,
      totalCount: 0
    }
  }),

  getters: {
    // 获取筛选后的衣物列表
    filteredClothes: (state) => {
      return state.clothesList.filter(clothes => {
        // 类型筛选
        if (state.filters.type && clothes.type !== state.filters.type) {
          return false;
        }

        // 颜色筛选
        if (state.filters.color && clothes.color !== state.filters.color) {
          return false;
        }

        // 季节筛选
        if (state.filters.season && !clothes.season.includes(state.filters.season)) {
          return false;
        }

        // 场合筛选
        if (state.filters.occasion && !clothes.occasions.includes(state.filters.occasion)) {
          return false;
        }

        // 收藏筛选
        if (state.filters.favorite && !clothes.isFavorite) {
          return false;
        }

        return true;
      });
    },

    // 获取衣物分类统计
    categoryStats: (state) => {
      const stats = {};
      state.clothesList.forEach(clothes => {
        const type = clothes.type[0].text
        // 使用type属性作为分类依据
        if (!stats[type]) {
          stats[type] = 0;
        }
        stats[type]++;
      });
      return stats;
    },

    // 获取季节统计
    seasonStats: (state) => {
      const stats = {
        '春': 0,
        '夏': 0,
        '秋': 0,
        '冬': 0
      };

      state.clothesList.forEach(clothes => {
        if (clothes.season && Array.isArray(clothes.season)) {
          clothes.season.forEach(season => {
            if (stats.hasOwnProperty(season)) {
              stats[season]++;
            }
          });
        }
      });

      return stats;
    },

    // 获取所有颜色列表
    allColors: (state) => {
      const colors = new Set();
      state.clothesList.forEach(clothes => {
        colors.add(clothes.color);
      });
      return Array.from(colors);
    }
  },

  actions: {
    // 设置筛选条件
    setFilters(filters) {
      this.filters = { ...this.filters, ...filters };
      this.pagination.currentPage = 1;
    },

    // 重置筛选条件
    resetFilters() {
      this.filters = {
        type: '',
        color: '',
        season: '',
        occasion: '',
        favorite: false
      };
      this.pagination.currentPage = 1;
    },

    // 获取衣物列表
    async fetchClothesList() {
      try {
        this.loading = true;
        this.error = null;

        // 构建查询参数
        const params = {
          page: this.pagination.currentPage,
          pageSize: this.pagination.pageSize,
          ...this.filters
        };

        const response = await axios.get('/clothes', { params });

        this.clothesList = response.items;
        this.pagination.totalCount = response.total;

        return response;
      } catch (error) {
        this.error = error.response?.data?.message || '获取衣物列表失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 获取单个衣物详情
    async fetchClothesDetail(id) {
      try {
        this.loading = true;
        this.error = null;

        const response = await axios.get(`/clothes/${id}`);

        this.selectedClothes = response;

        return response;
      } catch (error) {
        this.error = error.response?.data?.message || '获取衣物详情失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 添加衣物
    async addClothes(clothesData) {
      try {
        this.loading = true;
        this.error = null;

        const response = await axios.post('/clothes', clothesData);

        // 添加到本地列表
        this.clothesList.unshift(response);

        return response;
      } catch (error) {
        this.error = error.response?.data?.message || '添加衣物失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 更新衣物
    async updateClothes(id, clothesData) {
      try {
        this.loading = true;
        this.error = null;

        const response = await axios.put(`/clothes/${id}`, clothesData);

        // 更新本地列表
        const index = this.clothesList.findIndex(item => item._id === id);
        if (index !== -1) {
          this.clothesList[index] = response;
        }

        // 更新当前选中的衣物
        if (this.selectedClothes && this.selectedClothes._id === id) {
          this.selectedClothes = response;
        }

        return response;
      } catch (error) {
        this.error = error.response?.data?.message || '更新衣物失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 删除衣物
    async deleteClothes(id) {
      try {
        this.loading = true;
        this.error = null;

        await axios.delete(`/clothes/${id}`);

        // 从本地列表中移除
        this.clothesList = this.clothesList.filter(item => item._id !== id);

        // 清除选中状态
        if (this.selectedClothes && this.selectedClothes._id === id) {
          this.selectedClothes = null;
        }

        return true;
      } catch (error) {
        this.error = error.response?.data?.message || '删除衣物失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 批量删除衣物
    async deleteMultipleClothes(ids) {
      try {
        this.loading = true;
        this.error = null;

        await axios.post('/clothes/batch/delete', { ids });

        // 从本地列表中移除所有指定的衣物
        this.clothesList = this.clothesList.filter(item => !ids.includes(item._id));

        // 如果选中的衣物在删除列表中，清除选中状态
        if (this.selectedClothes && ids.includes(this.selectedClothes._id)) {
          this.selectedClothes = null;
        }

        return true;
      } catch (error) {
        this.error = error.response?.data?.message || '批量删除衣物失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 增加穿着次数
    async incrementWearCount(id) {
      try {
        this.loading = true;
        this.error = null;

        const response = await axios.patch(`/clothes/${id}/wear`);

        // 更新本地数据
        const index = this.clothesList.findIndex(item => item._id === id);
        if (index !== -1) {
          this.clothesList[index] = {
            ...this.clothesList[index],
            wearCount: (this.clothesList[index].wearCount || 0) + 1,
            lastWorn: new Date().toISOString().split('T')[0]
          };
        }

        // 更新选中的衣物
        if (this.selectedClothes && this.selectedClothes._id === id) {
          this.selectedClothes = {
            ...this.selectedClothes,
            wearCount: (this.selectedClothes.wearCount || 0) + 1,
            lastWorn: new Date().toISOString().split('T')[0]
          };
        }

        return response;
      } catch (error) {
        this.error = error.response?.data?.message || '更新穿着次数失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 切换收藏状态
    async toggleFavorite(id) {

      try {
        // 设置加载状态
        this.loading = true;
        this.error = null;

        const clothes = this.clothesList.find(item => item._id === id) || this.selectedClothes;
        if (!clothes) {
          this.error = '未找到指定衣物';
          return;
        }

        const newFavoriteState = !clothes.isFavorite;

        const response = await axios.patch(`/clothes/${id}/favorite`, {
          isFavorite: newFavoriteState
        });

        // 更新本地状态
        if (clothes) {
          clothes.isFavorite = newFavoriteState;
        }

        return response;
      } catch (error) {
        this.error = error.response?.data?.message || '切换收藏状态失败';
        console.error('收藏操作错误:', error);
        throw error;
      } finally {
        // 确保加载状态被重置
        this.loading = false;
      }
    },

    // 上传衣物图片
    async uploadImage(formData) {
      try {
        this.loading = true;
        this.error = null;

        const response = await axios.post('/clothes/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });

        return response;
      } catch (error) {
        this.error = error.response?.data?.message || '上传图片失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 清除错误信息
    clearError() {
      this.error = null;
    }
  }
});